package com.czp.opensource.profiler;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;
import java.util.List;

import com.czp.opensource.profiler.cfg.Configuration;
import com.czp.opensource.profiler.filter.InjectionFilter;
import com.czp.opensource.profiler.log.LogWrapper;


/**
 * 
 * @description 
 *        <p>整个profiler的入口,注入应用的main方法</p>
 * @author
 *         Czp
 * @version 
 *        1.0(2014-5-10)
 */
public class Injection implements ClassFileTransformer{
    
	private List<InjectionFilter> filters;
	
	public Injection() {
		filters = Configuration.loadFilter();
		LogWrapper.getInstance().start();
	}
	/**
	 * 
	 * @desc:
	 *     <p>注入main方法</p> 
	 * @param agentOps
	 * @param inst
	 */
	public static void premain(String agentOps, Instrumentation inst){
		inst.addTransformer(new Injection());
	}

	@Override
	public byte[] transform(ClassLoader loader, String className,
			Class<?> classBeingRedefined, ProtectionDomain protectionDomain,
			byte[] classfileBuffer) throws IllegalClassFormatException {
		String clsName = className.replaceAll("/", ".");
		for (InjectionFilter inj : filters) {
			if(inj.greedyMatch(clsName))
			{
				classfileBuffer = inj.doInject(clsName,classfileBuffer);
			}	
		}
		return classfileBuffer;
	}  
}
